import Request from 'luch-request';
import { useUserStore } from '../stores/user';

const http = new Request({
  baseURL: 'https://consult-api.itheima.net',
  custom: {
	  loading: true,
	  loadingText: '加载中...',
  }
  })
  
const tabBarList = [
	'pages/index/index',
	'pages/wiki/index',
	'pages/notify/index',
	'pages/my/index',
]

// 接口白名单，不需要token
const whiteList = [
	'/login',
	'/code',
	'/login/password',
]


http.interceptors.request.use((config) => {
	// 加载
	if (config.custom.loading) {
		uni.showLoading({
			title: config.custom.loadingText,
		})
	}
	
	console.log(config.url);
	
	// 在js里面 store要求 哪里使用在哪里定义
	const userStore = useUserStore();
	const defaultHeader = {}
	if (userStore.token && !whiteList.includes(config.url) ) {
		// defaultHeader.Authorization = 'Bearer ' + userStore.token;
	}
	
	config.header = {
		// 'Authorization': '11111',
		...defaultHeader,
		...config.header
	}
	return config; // 如果不需要更改请求头信息，直接返回config
})




// ✅ 正确写法
http.interceptors.response.use(
  (response) => {
    uni.hideLoading();
    return response.data;
  },
  function(error) {
    uni.hideLoading();
    
    // if (error.statusCode === 401) reLogin();
    return Promise.reject(error);

    // 引导用户登录
    function reLogin() {
      const pageStack = getCurrentPages();
      const currentPage = pageStack[pageStack.length - 1];
      const redirectURL = currentPage.$page.fullPath;
      const openType = tabBarList.includes(currentPage.route) ? 'switchTab' : 'redirectTo';
      
      const userStore = useUserStore();
      userStore.redirectURL = redirectURL;
      userStore.openType = openType;
      
      uni.redirectTo({
        url: '/pages/login/index'
      });
    }
  } // 错误回调函数闭合
); // use() 方法调用闭合



  export { http}